package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.MenuDao;
import com.itheima.dao.PermissionDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.Permission;
import com.itheima.service.PermissionService;
import com.itheima.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = PermissionService.class)
@Transactional
public class PermissionServiceImpl implements PermissionService {

    @Autowired
    private PermissionDao permissionDao;

    //查询所有权限
    @Override
    public List<Permission> findAll() {
        return permissionDao.findAll();
    }

    //带条件查询权限信息
    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        int currentPage = queryPageBean.getCurrentPage();
        int pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();
        PageHelper.startPage(currentPage, pageSize);
        Page<Permission> page = permissionDao.findByCondition(queryString);

        Long total = page.getTotal();
        List rows = page.getResult();


        return new PageResult(total, rows);
    }

    //添加新权限
    @Override
    public void add(Permission permission) {

        Date date = new Date();

        permission.setCreatedate(date);

        permissionDao.add(permission);

    }

    @Override
    public Permission findById(Integer permissionId) {
        return permissionDao.findById(permissionId);
    }

    @Override
    public void edit(Permission permission) {
        //保存编辑信息
        permissionDao.edit(permission);
    }

    @Override
    public void deleteById(Integer id) {
        //检查删除id是否和角色表有关联
        List<Integer> list =  permissionDao.findRoleIdsByPermissionId(id);

        if (!list.isEmpty()) {
            throw new RuntimeException("用户和"+list.size()+"个角色相关联");
        }else {
            permissionDao.deleteById(id);
        }
    }

    @Override
    public void changeStatus(Map<String, Object> map) {
        Integer id = (Integer) map.get("id");
        String station = (String) map.get("station");
         permissionDao.changeStatus(id,station);

    }
}
